package com.coffee.controller;
import com.coffee.common.BaseContext;
import com.coffee.entity.R;
import com.coffee.entity.User;
import com.coffee.service.UserService;
import com.coffee.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 手机端的登录功能
     * @param userParam
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody User userParam){
        //md5加密密码
        userParam.setPassword(DigestUtils.md5DigestAsHex(userParam.getPassword().getBytes()));
        //查询用户信息
        User user = userService.login(userParam);
        if(user != null){ //用户名密码正确
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            claims.put("name",user.getName());

            //生成JWT令牌
            String jwt = JwtUtils.generateJwt(claims);
            return R.success(jwt);
        }
        return R.error("用户名或密码错误");
    }

    /**
     * 手机端的注册功能
     * @param userParam
     * @return
     */
    @PostMapping("/register")
    public R register(@RequestBody User userParam) {
        //新增用户
        userService.register(userParam);
        return R.success("注册成功");
    }

    /**
     * 手机端的退出登录功能
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout() {
        //删除threadlocal的id
        BaseContext.remove();
        return R.success("退出成功");
    }

    /**
     * PC端用户管理查询用户列表
     * @return
     */
    @PostMapping("/list")
    public R list () {
        List<User> userList = userService.list();
        return R.success(userList);
    }

    /**
     * PC端用户管理修改用户状态
     * @param user
     * @return
     */
    @PostMapping("/status")
    public R status(@RequestBody User user) {
        userService.status(user);
        return R.success(user);
    }
}
